//@Login && Register
const express = require('express')
const router = express.Router()
const Profile = require('../../models/Profile')
const passport = require('passport')

// $route GET api/profiles/test
// @desc return req's JSON
// @access public
router.get("/test", (req,res) => {
  res.json({
    msg: "profile works"
  })
})

// $route POST api/profiles/add
// @desc create or add a new Info
// @access private
router.post("/add",passport.authenticate('jwt',{session:false}), (req,res) => {
  const profileFiles = {}
  if(req.body.type) profileFiles.type = req.body.type
  if(req.body.describe) profileFiles.describe = req.body.describe
  if(req.body.income) profileFiles.income = req.body.income
  if(req.body.expend) profileFiles.expend = req.body.expend
  if(req.body.remark) profileFiles.remark = req.body.remark
  if(req.body.cash) profileFiles.cash = req.body.cash

  new Profile(profileFiles).save().then(profile => {
    res.json(profile) 
  })
})

// $route GET api/profiles/
// @desc get all info of profiles
// @access private
router.get("/",passport.authenticate('jwt',{session:false}), (req,res) => {
  Profile.find().then(profiles => {
    if(!profiles) {
      return res.status(404).json("without nothing!")
    }
    res.json(profiles)
  }).catch(err => {
    res.status(404).json(err)
  })
})

// $route GET api/profiles/:id
// @desc get one info of profiles
// @access private
router.get("/:id",passport.authenticate('jwt',{session:false}), (req,res) => {
  Profile.findOne({_id: req.params.id}).then(profiles => {
    if(!profiles) {
      return res.status(404).json("without nothing!")
    }
    res.json(profiles)
  }).catch(err => {
    res.status(404).json(err)
  })
})

// $route POST api/profiles/edit
// @desc edit or delete a new Info
// @access private
router.post("/edit/:id",passport.authenticate('jwt',{session:false}), (req,res) => {
  const profileFiles = {}
  if(req.body.type) profileFiles.type = req.body.type
  if(req.body.describe) profileFiles.describe = req.body.describe
  if(req.body.income) profileFiles.income = req.body.income
  if(req.body.expend) profileFiles.expend = req.body.expend
  if(req.body.remark) profileFiles.remark = req.body.remark
  if(req.body.cash) profileFiles.cash = req.body.cash

  Profile.findOneAndUpdate(
    {_id: req.params.id},
    {$set: profileFiles},
    {new: true},
  ).then(profile => res.json(profile))
})

// $route POST api/profiles/delete
// @desc edit or delete a new Info
// @access private
router.delete("/delete/:id",passport.authenticate('jwt',{session:false}), (req,res) => {
  Profile.findOneAndRemove({_id: req.params.id}).then(profile => {
    res.json(profile)
  }).catch(err => {
    res.status(404).json("删除失败！")
  })
})

module.exports = router